package com.example.server.service;

import com.example.server.gen.GreeterGrpc;
import com.example.server.gen.HelloReply;
import com.example.server.gen.HelloRequest;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Service
public class HelloWorldClient {

    private GreeterGrpc.GreeterBlockingStub stub;

    @Value("${grpc.hello-world.host}")
    private String host;
    @Value("${grpc.hello-world.port}")
    private Integer port;

    @PostConstruct
    void init() {
        ManagedChannel channel =
                ManagedChannelBuilder.forAddress(host, port)
                        .keepAliveWithoutCalls(true)
                        .keepAliveTime(60, TimeUnit.SECONDS)
                        .keepAliveTimeout(3, TimeUnit.SECONDS)
                        .idleTimeout(60, TimeUnit.SECONDS)
                        .maxInboundMessageSize(Integer.MAX_VALUE)
                        .usePlaintext().build();
        stub = GreeterGrpc.newBlockingStub(channel);
    }

    /**
     * 说“你好”
     *
     * @param name 名字
     * @return {@link String}
     */
    public String sayHello(String name) {

        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloReply helloReply = stub.sayHello(request);
        return helloReply.getMessage();
    }
}